@attribute [Authorize(Roles="Employee")]
@inherits AppAuthComponentBase

<form @onsubmit="_ => OnSubmit()" class=@CssUtils.ClassNames("relative shadow rounded p-4", @class)>
<CascadingValue Value=@api.Error>
    <button type="button" class="close" @onclick="close"><i></i></button>

    <h1 class="fs-4 text-secondary text-center">
        Edit Booking
    </h1>

    <ErrorSummary Except=@VisibleFields />
    <ErrorSummary ExplicitStatus=@deleteApi.Error />

    <div class="mb-3 form-floating">
        <TextInput @bind-Value="request.Name" required placeholder="Name for this booking" />
    </div>

    <div class="mb-3 form-floating">
        <SelectInput @bind-Value="request.RoomType" Options=@(Enum.GetValues<RoomType>().Cast<RoomType?>()) /> 
    </div>

    <div class="d-flex">
        <div class="mb-3 flex-fill form-floating me-1">
            <TextInput type="number" @bind-Value="request.RoomNumber" min="0" required />
        </div>

        <div class="mb-3 flex-fill form-floating">
            <TextInput type="number" @bind-Value="request.Cost" min="0" required />
        </div>
    </div>

    <div class="d-flex">
        <div class="mb-3 flex-fill form-floating me-1">
            <DateTimeInput @bind-Value="request.BookingStartDate" required />
        </div>

        <div class="mb-3 flex-fill form-floating">
            <DateTimeInput @bind-Value="request.BookingEndDate" />
        </div>
    </div>
    
    <div class="mb-3 form-floating">
        <TextAreaInput @bind-Value="request.Notes" placeholder="Notes about this booking" style="height:6rem" />
    </div>

    <div class="d-flex justify-content-between align-items-center">
        <div>
            <input type="checkbox" @bind=deleteConfirmed id="deleteConfirmed" />
            <label for="deleteConfirmed">confirm</label>
            <span class=@ClassNames("ms-2 btn btn-danger", deleteConfirmed ? "" : "disabled") @onclick="delete">Delete</span>
        </div>

        <div class="d-flex-fill">
            <SrcLink href="https://github.com/NetCoreTemplates/blazor-wasm/blob/master/MyApp.Client/Pages/BookingsCrud/Edit.razor" 
                     IconSrc="/img/blazor.svg" class="mt-2" />
        </div>

        <div>
            <button type="submit" class="btn btn-primary">Update Booking</button>
        </div>
    </div>

</CascadingValue>
</form>


@if (api.Succeeded) {
    <h3 class="text-success mt-4">@api.Response!.Id</h3>
}

@code {
    [Parameter] public int? Id { get; set; }
    [Parameter] public EventCallback<IdResponse> done { get; set; }

    // Hide Error Summary Messages for Visible Fields which displays contextual validation errors
    string[] VisibleFields => new[] {
        nameof(request.Name),
        nameof(request.RoomType),
        nameof(request.RoomNumber),
        nameof(request.BookingStartDate),
        nameof(request.BookingEndDate),
        nameof(request.Cost),
        nameof(request.Notes),
    };

    bool deleteConfirmed = false;

    UpdateBooking request = new();

    async Task refresh()
    {
        var selectApiResult = await ApiAsync(new QueryBookings { Id = Id });
        if (selectApiResult.Failed)
        {
            api = ApiResult.CreateError<IdResponse>(selectApiResult.Error!);
            return;
        }

        if (selectApiResult.Response!.Results.Count == 0)
        {
            api = ApiResult.CreateError<IdResponse>($"Booking #{Id} does not exist");
            return;
        }

        var booking = selectApiResult.Response!.Results[0];
        request = new UpdateBooking
        {
            Id = booking.Id,
            Name = booking.Name,
            RoomType = booking.RoomType,
            RoomNumber = booking.RoomNumber,
            BookingStartDate = booking.BookingStartDate,
            BookingEndDate = booking.BookingEndDate,
            Cost = booking.Cost,
            Notes = booking.Notes,
        };
    }

    protected override async Task OnInitializedAsync() => await refresh();

    async Task close() => await done.InvokeAsync(null);

    ApiResult<IdResponse> api = new();

    async Task OnSubmit()
    {
        api = await ApiAsync(request);

        if (api.Succeeded)
        {
            await done.InvokeAsync(api.Response!);
        }
    }

    ApiResult<EmptyResponse> deleteApi = new();

    async Task delete()
    {
        if (!deleteConfirmed)
            return;

        deleteApi = await ApiAsync(new DeleteBooking { Id = Id ?? 0 });

        if (deleteApi.Succeeded)
            await close();
    }
}
